(function() {
  app.controller('searchCtrl', function($scope, $rootScope, quoteApi, tradeApi, my_zxg_v, $state, $stateParams, local_m) {
    $scope.serch_history = $scope.storage.local('serch_history') || [];
    var my_zxg;
    $scope.init = function() {
      my_zxg_v
        .updata()
        .then(function(res) {
          my_zxg = res;
          for (var i = 0; i < $scope.serch_history.length; i++) {
            $scope.serch_history[i].flag = false;
            for (var j = 0; j < res.length; j++) {
              if ($scope.serch_history[i].code === res[j].code) {
                $scope.serch_history[i].flag = true;
              }
            }
          }
        });
      $scope.create_button = $stateParams.type === 'zixuan' ? false : true
    };


    $scope.stkinfo = { code: '' };
    var watcher = $scope.$watch('stkinfo.code', function(newValue, oldValue) {
      if ($scope.stkinfo.code === '') {
        $scope.search_result = null;
        return;
      }
      tradeApi.query({
        funcId: '000010',
        data: {
          product_code: newValue,
          count: 10
        }
      }).then(function(res) {
        if (!res) return;

        for (var i = 0; i < res.length; i++) {
          res[i].flag = false;
          res[i].code = res[i].product_code;
          res[i].name = res[i].product_name;
          delete res[i].product_code;
          delete res[i].product_name;
          res[i].style = 2;
          for (var j = 0; j < my_zxg.length; j++) {
            if (res[i].code === my_zxg[j].code) {
              res[i].flag = true;
            }
          }
        }
        $scope.search_result = res;
      });
    });

    $scope.click_result = function(item) {
      $scope.go_detail(item);
    };

    $scope.del_search_history = function() {
      $scope.serch_history = [];
      $scope.storage.local('serch_history', $scope.serch_history);
    };

    $scope.add_my_zxg = function(item) {
      var copyed = angular.copy(item);
      my_zxg_v
        .set(copyed, { toggle: true })
        .then(function(res) {
          item.flag = !item.flag;
          $scope.init();
        });
    };

    $scope.go_detail = function(item) {
      for (var i = 0; i < $scope.serch_history.length; i++) {
        if (item.code === $scope.serch_history[i].code) {
          $scope.serch_history.splice(i, 1);
          break;
        }
      }
      $scope.serch_history.unshift(item);
      $scope.storage.local('serch_history', $scope.serch_history);
      $scope.storage.local('detail_codeinfo', item);
      $state.go('detail', { type: $stateParams.type || '' });
    };

    $scope.create = function(item) {
      $scope.storage.local('detail_codeinfo', item);
      $state.go('strategy', { type: $stateParams.type || '' });
    }
    $scope.$on('$destroy', function() {
      watcher();
    });
  });
})();